import { onBeforeUnmount, onMounted } from "vue";

type Listener = (this: Window, ev: WindowEventMap[keyof WindowEventMap]) => any;
export default function useResize(onResize: Listener) {
    onMounted(() => {
        window.addEventListener("resize", onResize);
    });
    onBeforeUnmount(() => {
        window.removeEventListener("resize", onResize);
    });
}

function useResizeObserver(
    selector: string,
    handle: (args: ResizeObserverEntry[]) => void,
) {
    let resizeObserver: ResizeObserver;
    let el: HTMLElement | null;
    onMounted(() => {
        resizeObserver = new ResizeObserver((entries) => {
            handle && handle(entries);
        });
        el = document.querySelector(selector);
        if (el) {
            resizeObserver.observe(el);
        }
    });
    onBeforeUnmount(() => {
        el && resizeObserver && resizeObserver.unobserve(el);
    });
}

export { useResizeObserver };
